<?php
/**
 * Created by PhpStorm.
 * User: wym
 * Date: 2016/6/7
 * Time: 14:19
 */
//爱病例
class CaseController extends BaseController{

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);

        $this->redirectToWeixinForOpenid();
    }
    //列表页
    function index(){
        $case_list_url = $this->url('case','index');
        $case_add_url = $this->url('case','case_add');
        $case_detail_url = $this->url('case','case_detail');


        $搜索 = "";
        if($_POST['标题']){
            $搜索['标题'] = $_POST['标题'];
        }
        $_GET['zt'] = $_GET['zt'] == "" ?"id":$_GET['zt'];
        $do_case = new Do病历文章();
        $do_user = new Do用户();
        $do_case->leftJoin($do_user,'b','a.`添加用户id` = b.id');
        $where="";

        if($_REQUEST['标题']!=null){

            $where = "  a.title like '%".$_REQUEST['标题']."%'";
        }else{
            if(isset($_GET['an']) && $_GET['an'] ==='已回答'){

                $where="   a.评论次数>0 ";
            } else if(isset($_GET['an']) && $_GET['an'] ==='待回答'){
                $where="  a.评论次数=0 ";
            }

            if(@$_GET['zt']){
                $order="  a.".@$_GET['zt']." DESC ";
            }
        }

        $case_count=$do_case->fields("count('id')")->where($where)->getOneField();
        $page=new tools\Page($case_count,10);
        $case_list= $do_case->fields(' a.*,b.`name`,b.`头像`')->where($where)->orderby($order)->offset($page->limit)->limit($page->pagesize)->rows();

        require $this->template;
    }

    //病例添加
    function  case_add()
    {
        $do_user = new Do用户();
        $case_list_url = $this->url('case', 'index');
        $register_url = $this->url('user','user_register');
        $res_usr_one = $do_user->fields('密码,认证')->row($_SESSION['vo用户数据']['id']);
        if ($res_usr_one->data['密码'] == "") {
            echo "<script>alert('请加入爱贝医生才能查看哦');window.location.href= '" . $register_url . "';</script>";
            die;
        }

        $renzheng_url = $this->url('user','user_base');
        if ($res_usr_one->data['认证'] == 1 || !$res_usr_one->data['认证'] || $res_usr_one->data['认证'] == '' || $res_usr_one->data['认证'] === '') {
            echo "<script>alert('请先加入爱贝医生');window.location.href= '" . $renzheng_url . "';</script>";
            die;
        }

        //所有区域
        $do_area = new Do区域();
        $area_list = $do_area->rows();
        #处理提交表单
        if (isset($_POST['okn'])) {
            $title = $this->request('title', "", true);
            $do_bingli = new Do病历文章();
            $do_bingli->set_title($title);
            $do_bingli->set_关键词($this->request('关键词'));
            $do_bingli->set_区域id($this->request('区域id'));
            $do_bingli->set_医院id($this->request('医院id'));
            $do_bingli->set_详情($this->request('content'));
            $do_bingli->set_添加用户id($_SESSION['vo用户数据']['id']);
            $add_res = $do_bingli->save();
            $last_id = $do_bingli->get_id();
            $img_url = 'cache/BingliAS_img/';
            $图片 = Tools::upload_imgs($_FILES, $img_url, 'pic'); //$bm -> 多图上传();
            $do = new Do病历文章();
            $do->set_t1($图片[0]);
            $do->set_t2($图片[1]);
            $do->set_t3($图片[2]);
            $do->set_t4($图片[3]);
            $do->set_t5($图片[4]);
            $do->set_id($last_id);
            $do->update();
            if ($add_res) {
                echo "<script>alert('添加病历成功');location.replace(location.href='" . $case_list_url . "');</script>";
            } else {
                echo "<script>alert('添加病例失败');</script>";
            }
        }

        require $this->template;
    }

    //查看病例详情
    function  case_detail(){


        $do_bingli = new Do病历文章();
        $do_user = new Do用户();
        $do_hospital = new Do医院();
        $do_area = new Do区域();
        //进入页面权限
        $register_url = $this->url('user','user_register');
        $renzheng_url = $this->url('user','user_base');
        $case_list_url = $this->url('case', 'index');
        $myself = $do_user->fields(' `密码`,`认证`')->row($_SESSION['vo用户数据']['id']);

        if (empty($myself->data['密码'])) {
                 exit( "<script>alert('请加入爱贝医生才能查看哦！');window.location.href= '".$register_url."';</script>");
        }

        if ($myself->data['认证'] == 1 || !$myself->data['认证'] || $myself->data['认证'] == '' || $myself->data['认证'] === '') {
            echo "<script>alert('请先加入爱贝医生');window.location.href= '".$renzheng_url."';</script>";
            die;
        }
        $do_bingli->leftJoin($do_user, 'b', 'a.`添加用户id` = b.id')
            ->leftJoin($do_hospital, 'c', 'a.`医院id` =c.id')
            ->leftJoin($do_area, 'd', 'a.`区域id` = d.id');

        $id = (isset($_GET['id'])) ? $_GET['id'] : "";

        $bingli_detail = $do_bingli
            ->fields('a.*,b.`name`,b.openID,b.`头像`,c.`医院`,b.description,d.`区域`')
            ->where(array('a.id' => $id))->row();
        //病历评论列表
        $param = array('a.id' => $id);
        $pinglun_list = $this->case_pinglun($id);
        if (isset($_POST['add'])) {
                if ($_POST['说明'] === '') {
                    echo "<script>alert('请输入内容');location.replace(location.href);</script>";
                } else {
                    //添加病历文章评论
                    $do_case_pinglun = new Do病历文章评论();
                    $do_case_pinglun->set_用户id($_SESSION['vo用户数据']['id']);
                    $do_case_pinglun->set_诊断($_POST['诊断']);
                    $do_case_pinglun->set_说明($_POST['说明']);

                    $do_case_pinglun->data['pid'] = intval($_POST['pid']);
                    $do_case_pinglun->set_文章id($_GET['id']);
                    $do_case_pinglun->set_时间(Date('Y-m-d H:i:s'));
                    $do_case_pinglun->set_表名('病历文章');

                    $case_pinglun_insert = $do_case_pinglun->save();
                    //修改病历文章评论次数
                    $do_bingli1 = new Do病历文章();
                    $do_bingli1->set_评论次数($bingli_detail->data['评论次数'] + 1);
                    $do_bingli1->set_id($_GET['id']);
                    $case_up = $do_bingli1->save();

                    //发送病例回复通知：$_POST['pid']==0;表示发表的评论，反之是回复的评论
                    if ($_POST['pid'] == 0) {
                        $receive_openID = $bingli_detail->data['openID'];
                    } else {
                        $where = array('a.id' => $_POST['pid']);
                        $arritem = $do_case_pinglun->fields(' a.*,b.`name`,b.`openID`')->where($where)->leftJoin($do_user, 'b', 'a.`用户id`= b.id')->row();

                        $receive_openID = $arritem->data['openID'];
                    }
                    if ($case_pinglun_insert) {
                        $this->ff发送病例回复通知文本消息_new($receive_openID, $_GET['id'], $bingli_detail->data);
                        logger()->logInfo(sprintf("病历回复通知文本消息：openeid:%s,病历id:%s,内容:%s",$receive_openID,$_GET['id'],$bingli_detail->date));
                        echo "<script>alert('发表成功');location.replace(location.href);</script>";
                    } else {
                        echo "<script>alert('发表失败');location.replace(location.href);</script>";
                    }
                }

        }else{

            #更新浏览数 1:病历文章
            article_statistic(1, $_SESSION['vo用户数据']['id'], $_GET['id']);

            //页面分享取参数
            $desc = mb_substr(strip_tags($bingli_detail->data['详情']), 0, 100, 'utf-8');
            $desc = str_replace('&nbsp', ' ', $desc);

            $avatar = trim($bingli_detail->data['头像']);
            if (!$avatar) {
                $avatar = G_SITE_CDN .'/business/img/default_avatar.jpg';
            }
            if (substr($avatar, 0, 4) != 'http') {
                $avatar = G_SITE_CDN .'/business/'. $avatar;
            }

            require $this->template;
        }
    }

    //病历评论列表
    function case_pinglun($case_id) {
        $do_course_pinglun = new Do病历文章评论();
        $do_user = new Do用户();
        $do_course_pinglun->leftJoin($do_user, 'b', 'a.`用户id`= b.id');

        $where = array('文章id' => $case_id, '表名' => '病历文章');
        $count = $do_course_pinglun->fields("count('a.id')")->where($where)->getOneField();
        $page_pinglun = new \tools\Page($count, 5);

        $arr['res'] = $do_course_pinglun
            ->fields('a.*,b.`name`,b.`头像` ')
            ->where($where)
            ->offset($page_pinglun->limit)
            ->limit($page_pinglun->pagesize)
            ->orderby('id ')->rows();

        foreach ($arr['res'] as $key => $value) {
            //$value['pid']==0：表示为评论消息，非零为回复消息
            if ($value['pid'] == 0) {
                continue;
            }

            $arritem = $do_course_pinglun->where(array('a.id' => $value['pid']))->row();

            $arr['res'][$key]['p头像'] = $arritem->data['头像'];
            $arr['res'][$key]['p用户id'] = $arritem->data['用户id'];
            $arr['res'][$key]['p说明'] = $arritem->data['说明'];
            $arr['res'][$key]['p表名'] = $arritem->data['表名'];
            $arr['res'][$key]['p头像'] = $arritem->data['头像'];
            $arr['res'][$key]['pname'] = $arritem->data['name'];
        }
        $arr['page'] = $page_pinglun->showpage_weixin();
        return $arr;
    }

    //病历回复发送文本消息
    public function ff发送病例回复通知文本消息_new($openid,$caseId,$病历文章)
    {
        $url = $this->url('case', 'case_detail',array('id' => $caseId));
        $infoUser = "您参与的病例讨论有新回复啦！<a href='$url'>点此查看</a>";
        $voCenter=C信息中心::get实列根据用户Oid($openid);
        $res = $voCenter->ff发送文本消息($infoUser,$openid);
        $result = json_decode($res);
        if($result->errmsg!="ok"){
            $this->ff病例回复模板消息($voCenter,$openid,$url,$病历文章);
        }
    }

    //病历回复模板消息
    public function ff病例回复模板消息(C信息中心 $voCenter,$openID,$url,$病历文章){
        $info = '您好！您参与的病例讨论有了新回复，点击查看';
        global $G_CONFIG;
        $date = date("Y-m-d H:i:s",time());
        $模板信息 = array(
            '咨询模板ID' => $G_CONFIG['模板消息ID']['问题回复通知'],
            'title' => $info,
            'content' => $病历文章['title'],
            'date' => $date,
        );
        $模板信息['咨询模板ID'] = trim($模板信息['咨询模板ID']);
        $发送模板结果= $voCenter->ff发送模板消息($模板信息['咨询模板ID'],$openID,array(
            'first'=>array('value'=> $模板信息['title'],'color'=>'#173177'),
            'keyword1'=>array('value'=>$模板信息['content'],'color'=>'#173177'),
            'keyword2'=>array('value'=> $模板信息['date'],'color'=>'#173177')
        ), G_SERV_ID,$url);

        return $发送模板结果;
    }


}